package sws;

import java.util.Random;

public class EmuSensor extends Thread {
	private static String[] conditions = {"dry", "wet", "icy"};
	private boolean alive = true;
	private String[] res;

	public EmuSensor(String[] mRes) {
		res = mRes;
	}

	public void run() {
		Random r = new Random();
		try {
			// Sensor bootup delay
			Thread.sleep(5000);

			while(alive) {
				double value = r.nextDouble();

				// Highest probability for dry road surface
				// Lowest probability for icy road surface
				if(value < .6)
					res[0] = conditions[0];
				else if(value < .85)
					res[0] = conditions[1];
				else
					res[0] = conditions[2];
			}
			res[0] = null;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Get data produced by the sensor, a small delay is included to simulate
	 * the expected response time from a ping to an echo.
	 * 
	 * @return String[1] containing the current road surface condition. 
	 */
	public String[] getData() {
		try {
			Thread.sleep(50);
		
			while(res[0] == null) {
				Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return new String[]{res[0]};
	}

	public void kill() {
		alive = false;
	}
}
